package androidx.test.uiautomator

import android.app.UiAutomation
import android.graphics.Bitmap
import com.wetest.uia2.stub.Log
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import uiautomator.InstrumentShellWrapper
import java.io.File


object UiAutomationHelper {
    val uiAutomation: UiAutomation
        get() = UiDevice.getInstance(InstrumentShellWrapper.getInstance()).uiAutomation

    var testApiService: TestApiService? = null

    fun createRetrofit() {
        if (testApiService == null) {
            // 初始化 Retrofit
            val retrofit = Retrofit.Builder()
                .baseUrl("https://agent.aminer.cn") // 替换为实际的 base URL
                .addConverterFactory(GsonConverterFactory.create())
                .client(OkHttpClient.Builder().build())
                .build()

            // 创建 API 实例
            testApiService = retrofit.create(TestApiService::class.java)
        }
    }

    fun requestControl() {
        val headerMap = hashMapOf<String, String>()
        headerMap["X-Auth-Sign"] = "7e4cf03082156e7ce1b49503a1bbcabe"
        headerMap["X-Auth-TimeStamp"] = "1732678685"
        headerMap["X-Auth-Appid"] = "100001"
        headerMap["Authorization"] =
            "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjozMzExMCwiZGV2aWNlX2lkIjoiYmQwNTQxNGY5Njg3ODlkYiIsInN1YiI6IjE5ODAyMDIxNTQzIiwiZXhwIjoxNzM1MTk0MjEzLCJpYXQiOjE3MzI2MDIyMTMsImp0aSI6ImJkMDU0MTRmOTY4Nzg5ZGIifQ.arBHYeExX3dUtbiIYTgkDMY7RdTTPQVeejsJi7xNf9c"


        val paramsMap = hashMapOf<String, String>()
        paramsMap["layout_xml"] = "layout_xml"
        paramsMap["image"] = "asd.jpg"
        paramsMap["app_version"] = "1203"
        paramsMap["os"] = "Android"
        paramsMap["android_version"] = "13"
        paramsMap["platform"] = "1"
        paramsMap["instruction"] = "导航去三里屯"
        paramsMap["package_name"] = "com.miui.home"
        paramsMap["mine_package_name"] = "com.zhipu.agent"
        paramsMap["app_version_name"] = "1.2.03"
        paramsMap["brand"] = "Redmi"
        paramsMap["task_discriminate"] = "true"

        val arrayList = createPartsFromParams(paramsMap)

        testApiService?.uploadSync(headerMap, "/agentapi/v2/proxy/controller", arrayList)
            ?.enqueue(object : Callback<String> {
                override fun onResponse(p0: Call<String>, p1: retrofit2.Response<String>) {
                    if (p1.isSuccessful) {
                        Log.i(p1.body().toString())
                    }
                }

                override fun onFailure(p0: Call<String>, p1: Throwable) {

                }

            })
    }

    fun createPartsFromParams(paramsMap: Map<String, Any>): ArrayList<MultipartBody.Part> {
        val parts = ArrayList<MultipartBody.Part>()

        for ((key, value) in paramsMap) {
            val part: MultipartBody.Part = when {
                value is Bitmap && key.endsWith(".jpg") -> {
                    // 压缩 Bitmap 并创建 Part
                    val compressedBitmap = compressBitmapQuality(value, 10)
                    val bitmapRequestBody = RequestBody.create("image/jpeg".toMediaTypeOrNull(), compressedBitmap)
                    MultipartBody.Part.createFormData(key.replace(".jpg", ""), key, bitmapRequestBody)
                }
                value is File -> {
                    // 文件类型
                    val fileRequestBody = RequestBody.create("audio/pcm".toMediaTypeOrNull(), value)
                    MultipartBody.Part.createFormData(key, key, fileRequestBody)
                }
                else -> {
                    // 普通 String 参数
                    MultipartBody.Part.createFormData(key, value.toString())
                }
            }
            parts.add(part)
        }

        return parts
    }

    fun compressBitmapQuality(bitmap: Bitmap, quality: Int): ByteArray {
        val outputStream = java.io.ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
        return outputStream.toByteArray()
    }


    fun rpcDumpWindowHierarchy(): String? {
        // 创建 OkHttpClient 实例
        val client = OkHttpClient()

        // 定义 JSON 请求体
        val json = """
        {
            "jsonrpc": "2.0",
            "method": "dumpWindowHierarchy",
            "params": [true],
            "id": 1
        }
    """.trimIndent()

        // 定义请求体
        val requestBody = json.toRequestBody("application/json".toMediaType())

        // 构造请求
        val request = Request.Builder()
            .url("http://127.0.0.1:9009/jsonrpc/0")
            .post(requestBody)
            .build()

        runCatching {
            // 同步请求
            val response: Response = client.newCall(request).execute()
            // 处理响应
            if (response.isSuccessful) {
                val xml = response.body?.string()
                // 打印响应体
                println()
                return xml
            }
            // 关闭响应（确保资源释放）
            response.close()
        }
        return null
    }

}
